//
//  Status.swift
//  sinazd
//
//  Created by apple on 16/3/11.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import AFNetworking

class Status: NSObject {
    
    // 创建一个user属性
    var user: User?
    
    
    //微博创建的时间
    var created_at: String?
    
    // 在64机型上 默认的整形数据的长度 是64位的
    var id: Int64 = 0
    
    //微博正文
    var text: String?
    
    //微博来源
    var source: String?

    
    //重载init
    init(dict: [String: AnyObject]){
        super.init()
        self.setValuesForKeysWithDictionary(dict)
    
    }

    
    override func setValue(value: AnyObject?, forKey key: String) {
       
        if key == "user" {
            
            guard let dict = value as? [String: AnyObject] else {
                
                return
            }
            
            user = User(dict: dict)
            
            return
        }
        super.setValue(value, forKey: key)
    }

    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
}

//网络请求
extension Status {
    
    class func loadHomeData(finished:((array:[Status]?)->())) {
        
        guard let access_token = UserAccount.sharedAccount.access_token else {
            print("用户未登录或者登录过期")
            return
            
        }
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let parameters = ["access_token":access_token]
        
        let AFN = AFHTTPSessionManager()
        
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            guard let dic = result as? [String:AnyObject] else {
                finished(array: nil)
                print("数据获取错误")
                return
            }
            
            guard let array = dic["statuses"] as? [[String: AnyObject]] else {
                finished(array: nil)
                return
            }
            
            var tempArr = [Status]()
            
            for item in array {
                
                let s = Status(dict: item)
                
                tempArr.append(s)
                
            }
            
            finished(array: tempArr)
            
            
            
            }) { (_, error) -> Void in
                
                print(error)
                finished(array: nil)
        }
        
    }
    
    
}
